const bcrypt = require('bcryptjs')
const { db } = require('../../core/db')
const { Sequelize, Model } = require('sequelize')
const WXBizDataCrypt = require('../../core/WXBizDataCrypt')
class User extends Model {
  // 静态方法 verifyEmailPassword(email=邮箱号码,plainPassword=原始密码) 验证邮箱&原始密码是否存在
  static async verifyEmailPassword(email, plainPassword) {
    //通过User.findOne方法查询数据是否存在该邮箱
    const user = await User.findOne({
      where: {
        email,
      },
    })
    if (!user) {
      //不存在则抛出一个异常 AuthFailed
      throw new global.errs.AuthFailed('账号不存在')
    }
    // 把查询到的密码和用户提交的密码进行对比 bcrypt.compareSync(原始密码,加密后的密码)
    const correct = bcrypt.compareSync(plainPassword, user.password)
    if (!correct) {
      //不存在则抛出一个异常 AuthFailed
      throw new global.errs.AuthFailed('密码不正确')
    }
    // 存在则返回 user
    return user
  }
  // 静态方法 获取小程序用户的openid
  static async getUserByOpenid(openid) {
    //User.findOne 拿到小程序用户openid去数据库查询是否存在
    const user = await User.findOne({
      where: {
        openid,
      },
    })
    // 返回
    // if (!user) {
    //   //不存在则抛出一个异常 AuthFailed
    //   throw new global.errs.AuthFailed('用户未授权')
    // }
    // 存在则返回 user
    return user
  }
  // 静态方法 registerByOpenid(openid)
  static async registerByOpenid(openid) {
    // 用户openid存在则直接创建到数据库 并返回
    return await User.create({
      openid,
    })
  }
  // 静态方法 getUserDecodeOpenid
  static getUserDecodeOpenid(data={}){
    let {sessionKey,encryptedData,iv} = data
    let appId = global.config.wx.appid
    const pc = new WXBizDataCrypt(appId, sessionKey)
    const result = pc.decryptData(encryptedData , iv)
    if (!result) {
      throw new global.errs.AuthFailed('授权登录失败')
    }
    return data
  }
}
User.init(
  {
    id: {
      type: Sequelize.INTEGER,
      primaryKey: true,
      autoIncrement: true,
    },
    nickname: Sequelize.STRING(100),
    email: {
      type: Sequelize.STRING(128),
      unique: true,
    },
    password: {
      type: Sequelize.STRING,
      // model属性操作
      set(val) {
        // 生成盐
        const salt = bcrypt.genSaltSync(10)
        // 给密码加盐hashSync(原密码,salt)
        const psw = bcrypt.hashSync(val, salt)
        // 保存到数据库
        this.setDataValue('password', psw)
      },
    },
    openid: {
      type: Sequelize.STRING(64),
      unique: true,
    },
  },
  {
    sequelize: db,
    tableName: 'user',
  }
)

module.exports = {
  User,
}
